package gogo

import (
	"fmt"
	"net/http"
	"time"
)

var (
	phttpRouterHandler *httpRouterHandler
)

func init() {
	if phttpRouterHandler == nil {
		phttpRouterHandler = &httpRouterHandler{}
	}
}

// Run gorouter application.
// gorouter.Run() default run on HttpPort
// gorouter.Run("localhost")
// gorouter.Run(":8089")
// gorouter.Run("127.0.0.1:8089")
func Run(addr string) {
	var (
		endRunning = make(chan bool, 1)
	)

	go func() {
		fmt.Println("http server Running on ", addr)
		if err := http.ListenAndServe(addr, phttpRouterHandler); err != nil {
			fmt.Println("ListenAndServe: ", err)
			time.Sleep(100 * time.Microsecond)
			endRunning <- true
		}
	}()

	<-endRunning
	return
}

// GET 注册GET请求函数，注册固定URL、解析URL函数
// pattern string：触发路径
// handler httpProcFunc: 触发函数
func GET(pattern string, handler func(*HTTPContext)) {
	phttpRouterHandler.RegHTTPProcFunc("GET", pattern, handler)
}

// POST 注册POST请求函数，注册固定URL、解析URL函数
// pattern string：触发路径
// handler httpProcFunc: 触发函数
func POST(pattern string, handler func(*HTTPContext)) {
	phttpRouterHandler.RegHTTPProcFunc("POST", pattern, handler)
}

// PUT 注册PUT请求函数，注册固定URL、解析URL函数
// pattern string：触发路径
// handler httpProcFunc: 触发函数
func PUT(pattern string, handler func(*HTTPContext)) {
	phttpRouterHandler.RegHTTPProcFunc("PUT", pattern, handler)
}

// DELETE 注册DELETE请求函数，注册固定URL、解析URL函数
// pattern string：触发路径
// handler httpProcFunc: 触发函数
func DELETE(pattern string, handler func(*HTTPContext)) {
	phttpRouterHandler.RegHTTPProcFunc("DELETE", pattern, handler)
}

// STATUS 注册指定HTTP状态触发的函数
// status int：触发状态
// handler httpProcFunc: 触发函数
func STATUS(status int, handler func(*HTTPContext)) {
	phttpRouterHandler.RegHTTPStatusFunc(status, httpProcFunc(handler))
}
